package com.zs.mybatis.builder;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.zs.mybatis.config.Configuration;
import com.zs.mybatis.config.MappedStatement;
import com.zs.mybatis.factory.DefaultSqlSessionFactory;
import com.zs.mybatis.io.Resource;
import com.zs.mybatis.factory.SqlSessionFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class SqlSessionFactoryBuilder {
    private Configuration configuration;

    public SqlSessionFactoryBuilder() {
        this.configuration = new Configuration();
    }

    public SqlSessionFactory build(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        //解析xml文件，封装配置信息到configuration
        xmlConfigerBuilder(inputStream);
        SqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);
        return defaultSqlSessionFactory;
    }

    /*
     * @description:  解析核心配置文件
     * @param inputStream
     * @return: void
     * @author ZC
     * @date: 2021/11/6 15:07
     */
    private void xmlConfigerBuilder(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        //解析核心xml
        Document document = new SAXReader().read(inputStream);
        //获取根标签
        Element rootElement = document.getRootElement();
        //配置数据源
        Element dataSource = rootElement.element("dataSource");
        //获取到datasource下所有property标签
        List<Element> list = dataSource.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.put(name, value);
        }
        //创建连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        comboPooledDataSource.setUser(properties.getProperty("user"));
        configuration.setDataSource(comboPooledDataSource);
        //解析mapperw文件
        List<Element> mapperElements = rootElement.selectNodes("//mapper");
        xmlMapperBuilder(mapperElements);

    }

    private void xmlMapperBuilder(List<Element> mapperElements) throws DocumentException, ClassNotFoundException {
        for (Element mapperElement : mapperElements) {
            String resource = mapperElement.attributeValue("resource");
            InputStream inputStream = Resource.getInputStream(resource);
            parseMapper(inputStream);
        }
    }

    /*
     * @description: 解析所有mapper文件
     * @param inputStream
     * @return: void
     * @author ZC
     * @date: 2021/11/6 15:08
     */
    private void parseMapper(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);
        Element root = document.getRootElement();
        //获取命名空间对应的Mapper
        String classStr = root.attributeValue("namespace");
        //根据标签分别进行处理
        //获取select标签
        List<Element> select = root.selectNodes("select");
        for (Element element : select) {
            MappedStatement mappedStatement = new MappedStatement();
            // 解析标签各个值   <select id="selectOne" paramterType="com.zs.test.Dto.User" resultType="com.zs.test.Dto.User">
            String id = element.attributeValue("id");
            String paramterType = element.attributeValue("paramterType");
            String resultType = element.attributeValue("resultType");
            if (paramterType != null) {
                Class<?> parameterClass = Class.forName(paramterType);
                mappedStatement.setParameterType(parameterClass);
            }
            Class<?> resultClass = Class.forName(resultType);
            mappedStatement.setResultType(resultClass);
            String key = classStr + "." + id;
            mappedStatement.setId(key);
            String sql = element.getText();
            mappedStatement.setSql(sql);
            configuration.getMap().put(key, mappedStatement);
        }
    }


}
